/**
 * Created by xuxujunjunforever on 2015/12/2.
 */

'use strict'

let models = require('../models');

let UserDao = models.UserDao
let SchoolDao = models.SchoolDao;
let RoleDao = models.RoleDao;
let PrivilegeDao = models.PrivilegeDao;

let User = models.User;
let Privilege = models.Privilege;

function getUserInformation(user) {
    UserDao.refresh(user);
    RoleDao.refresh(user.role);
    SchoolDao.refresh(user.school);

    user.role.privileges.forEach(privilege=> {
        PrivilegeDao.refresh(privilege)
    });

    let plainObject = user.toObject();
    plainObject.school = user.school.toObject();
    plainObject.role = user.role.toObject();
    plainObject.role.privileges = Privilege.toObjectArray(user.role.privileges);

    delete plainObject.password;

    return plainObject;
}

function createUserOfRole(name, password, roleName) {
    let role = RoleDao.findOne({
        name: roleName
    });

    let user = new User({
        name: name,
        password: password,
        role: role,
        status: 1
    });
    UserDao.create(user);

    return user;
}

function createUser(userData) {
    let user = new User(userData);
    UserDao.create(user);

    return user;
}

function getUserByTelephone(telephone) {
    let user = UserDao.findOne({
        telephone: telephone
    });

    return user;
}

function updateUser(user) {
    return UserDao.update(user);
}

module.exports = {
    getUserInformation,
    createUserOfRole,
    createUser,
    getUserByTelephone,
    updateUser
};
